<template>
  <div class="carryway-and-address">
    <!-- <div v-if="type !== 'consign'" class="block">
      <header>
        <h2 class="required">
          订单类型
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item>
            <el-select v-model="ordertype" placeholder="请选择" @change="onChangeOrderType">
              <el-option
                v-for="item in order_type_ops"
                :key="item.orderTypeId"
                :label="item.orderTypeName"
                :value="item.ddbm"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </section>
    </div> -->
    <div class="block">
      <header>
        <h2 class="required">
          承运方式
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item>
            <el-radio-group v-model="carryway" @change="onChangeCarrayway">
              <el-radio
                v-for="item in rows_carryway"
                :key="item.enumKey"
                :label="item.enumKey"
              >
                {{ item.enumVal }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <div v-if="showAddress" class="block">
      <header>
        <h2 class="required">
          收货地址
        </h2>
        <el-divider direction="vertical" />
        <el-link type="primary" @click="openAddressAddDialog()">
          新增收货地址
        </el-link>
      </header>
      <section>
        <el-radio-group
          v-model="address"
          class="w100p address-group"
          @change="onChangeAddress"
        >
          <el-row v-for="item in rows_address" :key="item.id">
            <el-col
              class="address-item"
              :class="{ highline: item.id === address }"
            >
              <el-radio-button :label="item.id" class="title">
                <!-- <div class="name"> -->
                {{ item.userName }}
                <!-- </div> -->
              </el-radio-button>
              <el-divider direction="vertical" />
              <span class="detail">{{ item.userName }}</span>
              <el-divider direction="vertical" />
              <span class="detail">
                <span>{{ item.province }} {{ item.city }} {{ item.area }}</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item.detailedAddress"
                  placement="top-start"
                >
                  <span class="overflow-text">{{ item.detailedAddress }}</span>
                </el-tooltip>
              </span>
              <el-divider direction="vertical" />
              <span class="detail">{{ item.userPhone }}</span>
              <el-button
                v-if="item.id === address"
                size="small"
                type="text text-primary"
                style="margin-left:50px;font-weight: 600;"
                @click="openAddressAddDialog(item)"
                >编辑</el-button
              >
              <el-button
                v-if="item.id === address"
                size="small"
                type="text text-primary"
                style="color: red;"
                @click="deleteAddress(item.id)"
                >删除</el-button
              >
            </el-col>
          </el-row>
          <div v-if="showMoreAddress" class="more">
            <el-button
              v-if="toggleMoreAddress === false"
              type="text"
              @click="onClickMoreAddress"
            >
              更多地址
              <i class="el-icon-arrow-down" />
            </el-button>
            <el-button v-else type="text" @click="onClickLessAddress">
              收起
              <i class="el-icon-arrow-up" />
            </el-button>
          </div>
        </el-radio-group>
      </section>
    </div>
  </div>
</template>

<script>
import {
  commonEnum,
  getOrderAddressByUserId,
  deleteOrderAddress
} from '@api/m_mall_web_v1.js';
import { AddressAddDialogService } from '~/modules/address/address-add.dialog.module';

export default {
  props: {
    carrywayId: {
      type: String,
      default: ''
    },
    addressId: {
      type: String,
      default: ''
    },
    orderTypeId: {
      type: String,
      default: ''
    },
    payWayId: {
      type: String,
      default: ''
    },
    activeIndex: {
      type: Number,
      default: 0
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'wholesale'
    },
    allData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      order_type_ops: [],
      rows_carryway: [],
      rows_address_full: [],
      rows_address: [],
      rows_payway: [
        {
          key: '1',
          value: '在线支付（流程全自动化，迅速快捷下单，订单状态可跟踪）'
        },
        { key: '2', value: '线下支付（人工处理，此单使用积分、返利等）' }
      ],
      itemAddress: {},
      carryway: '',
      address: '',
      payway: '',
      ordertype: '',
      toggleMoreAddress: false,
      showMoreAddress: false,
      showAddress: true
    };
  },
  computed: {
    addressAddDialogService() {
      return new AddressAddDialogService(this.$axios);
    }
  },
  watch: {
    carrywayId: {
      handler(val) {
        this.carryway = val;
        // if (this.carryway === '1') {
        //   this.showAddress = false;
        // } else {
        this.showAddress = true;
        // }
      },
      immediate: true
    },
    addressId: {
      handler(val) {
        this.address = val;
        const address = this.rows_address.find(item => item.id === val);
        this.$emit('change-address', address);
      },
      immediate: true
    },
    orderTypeId: {
      handler(val) {
        this.ordertype = val;
      },
      immediate: true
    },
    payWayId: {
      handler(val) {
        this.payway = val;
      },
      immediate: true
    }
    // activeIndex: {
    //   handler: function(val, oldVal) {
    //     if (val === 3) {
    //       this.onGetOrderTypeData();
    //     }
    //   },
    //   immediate: true
    // }
  },
  async created() {
    this.$axios({
      method: 'post',
      url: commonEnum,
      data: { indexCode: 'transportType' }
    }).then(res => {
      this.rows_carryway = res.data.payload;
      this.rows_carryway[0].enumVal = '自提';
    });
    await this.reloadAddress(this.changeAddressList);
  },
  methods: {
    // onGetOrderTypeData() {
    //   this.$axios({
    //     url: commonGetOrderType,
    //     method: 'post',
    //     data: {
    //       busModel: 1,
    //       supplierCode: "111",
    //       page: 1,
    //       pageSize: 1000
    //     }
    //   }).then(res => {
    //     if (res.data.code === '0') {
    //       this.order_type_ops = res.data.payload;
    //     }
    //   });
    // },
    onChangeOrderType(value) {
      this.$emit('update:orderTypeId', value);
    },
    onChangeCarrayway(value) {
      this.$emit('update:carrywayId', value);
    },
    onChangePayWay(value) {
      this.$emit('update:payWayId', value);
    },
    onChangeAddress(value) {
      this.$emit('update:addressId', value);
      const address = this.rows_address.find(item => item.id === value);
      this.$emit('change-address', address);
    },
    onClickMoreAddress() {
      this.rows_address = this.rows_address_full;
      this.toggleMoreAddress = true;
    },
    onClickLessAddress() {
      this.rows_address = this.rows_address_full.slice(0, 3);
      this.toggleMoreAddress = false;
    },
    // 删除地址
    deleteAddress(id) {
      this.$confirm('是否要删除此收货地址？', '删除收货地址', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            id
          };
          this.$axios.$post(deleteOrderAddress, params).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.toggleMoreAddress = false;
            this.reloadAddress();
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    openAddressAddDialog(item) {
      if (item) {
        if (item.id) {
          this.itemAddress = item;
          this.addressAddDialogService
            .create({
              title: '新增收货地址',
              data: this.itemAddress,
              query: {},
              confirmButtonClickHandler: (data = {}) => {
                // 刷新完后，默认选中刚新增的记录上
                this.toggleMoreAddress = false;
                if (data) {
                  this.reloadAddress();
                }
              }
            })
            .mount();
        }
      } else {
        this.addressAddDialogService
          .create({
            title: '新增收货地址',
            query: {},
            confirmButtonClickHandler: (data = {}) => {
              // 刷新完后，默认选中刚新增的记录上
              this.toggleMoreAddress = false;
              if (data) {
                this.reloadAddress();
              }
            }
          })
          .mount();
      }
    },
    changeAddressList() {
      if (this.rows_address_full.length > 0) {
        let index = this.rows_address_full.findIndex(
          item => item.id === this.address
        );
        // console.log(this.rows_address_full, 'index')
        index = index < 0 ? 0 : index;
        this.rows_address_full.splice(
          0,
          0,
          this.rows_address_full.splice(index, 1)[0]
        );
      }
    },
    reloadAddress() {
      this.$axios({
        method: 'post',
        url: getOrderAddressByUserId
      }).then(res => {
        if (!res.data.code) return;
        this.rows_address_full = res.data.payload || [];
        // 存在地址列表
        if (this.rows_address_full.length) {
          // 且非编辑模式，那么就默认选中第一个
          if (!this.isEdit) {
            const address = this.rows_address_full[0];
            this.$emit('change-address', address);
            this.address = address.id;
            this.$emit('update:addressId', this.address);
          } else {
            this.$emit('update:addressId', this.address);
            const address = this.rows_address_full.find(
              item => item.id === this.address
            );
            // this.address = address.id;
            this.$emit('change-address', address);
          }
        } else {
          const address = {};
          address.area = '';
          address.city = '';
          address.province = '';
          address.detailedAddress = '';
          address.userPhone = '';
          address.userName = '';
          address.id = '';
          this.address = address.id;
          this.$emit('update:addressId', this.address);
          this.$emit('change-address', address);
        }
        if (this.isEdit === false) {
          this.rows_address = this.rows_address_full.slice(0, 3);
        } else {
          this.rows_address = this.rows_address_full;
        }
        this.showMoreAddress =
          this.rows_address_full.length > this.rows_address.length;
        // console.log(this.rows_address + '')
      });
    }
  }
};
</script>

<style lang="less">
.carryway-and-address {
  .address-group {
    font-size: inherit;
    .address-item {
      margin-bottom: 10px;
      .title .el-radio-button__inner {
        width: 120px;
        // .name {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        // }
      }
    }
    .more {
      width: 120px;
      text-align: center;
    }
  }
  .highline {
    color: #2371c5;
    font-weight: bold;
  }
  .overflow-text {
    display: inline-block;
    width: 24%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: -2px;
  }
}
</style>
